package com.gitee.ricesugar.mall.Fliter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/cart.jsp", "/order.jsp", "/content.jsp"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        Cookie[] cookies = ((HttpServletRequest) request).getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("login".equals(cookie.getName())) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}
